import { activeAnalysis, pageCuesActive } from '@/services/api/api-cues-active';
import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import { findTagColor } from '@/utils/findTagColor';
import {
  BarsOutlined,
  FileImageOutlined,
  MenuFoldOutlined,
  PaperClipOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import {
  LightFilter,
} from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Button, Cascader, Divider, Input, Popover, Space, Spin, Tabs, TabsProps, Tag, TreeSelect } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DetailsClue from './components/DetailsClue';
import './index.less'
import ProList from '@ant-design/pro-list';
import TableSubmit from '../../cues/topic/submit/TableSubmit';
import { parse } from '@/utils/historyUtils';

interface clueProps {
  reload: Boolean;
}


const Clue: React.FC<clueProps> = ({ reload }) => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  const [showList, setShowListState] = useState(false);

  const userRefList = useRef<ActionType>();

  useEffect(() => {
    if (reload) {
      userRefList.current?.reload()
    }
  }, [reload])

  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {

    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) { }
  };

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesActiveData.Analysis>();
  const [tabActiveKey, setTabActiveKeyState] = useState<string>('TableActive');

  useEffect(() => {
    treeOrganizationData();
    analysisData();
  }, []);
  /**
   * 加载 单位 列表
   * @param key
   */
  const analysisData = async () => {
    try {
      const response = await activeAnalysis();
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false);
        setTotalDataState(response.data);
      }
    } catch (error) { }
  };

  const items: TabsProps['items'] = [
    {
      key: 'TableActive',
      label: '主动报送',
    },
    {
      key: 'TableSubmit',
      label: '选题报送',
    },
  ];
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  return (
    <div>
      <Tabs defaultActiveKey="1" activeKey={tabActiveKey} onChange={setTabActiveKeyState} style={{ marginTop: -20 }}>
        <Tabs.TabPane tab="主动报送线索" key="TableActive"></Tabs.TabPane>
        <Tabs.TabPane tab="选题报送线索" key="TableSubmit"></Tabs.TabPane>
      </Tabs>
      {tabActiveKey === 'TableActive' && (
        <div>
          <Input.Search
            placeholder="查询标题"
            enterButton="搜索"
            allowClear
            style={{ maxWidth: 522, width: '100%' }}
            onChange={(e) => {
              setQueryParamState({ ...queryParam, articleName: e.target.value });
            }}
            onSearch={(value) => {
              userRefList.current?.reset();
            }}
          />
          <LightFilter
            // initialValues={{ run: 2 }}
            onValuesChange={(value) => {
              setQueryParamState(value);
              userRefList.current?.reset();
            }}
          >
            {/* <ProFormTreeSelect
              name="articleOrganizationIds"
              label="报送单位"
              width="xl"
              placeholder="选择单位"
              fieldProps={{
                treeData: articleOrganizations,
                treeCheckable: true,
                multiple: true,
                maxTagCount: 'responsive',
                // showCheckedStrategy: TreeSelect.SHOW_ALL,
              }}
              // fieldProps={{
              //   options: articleOrganizations,
              //   showSearch: { filter },
              //   multiple: true,
              //   removeIcon: true,
              //   allowClear: true,
              //   maxTagCount: 'responsive',
              //   showCheckedStrategy: Cascader.SHOW_CHILD,
              //   onChange(value, selectOptions) {
              //     setQueryParamState({ ...queryParam, articleOrganizationIds: value });
              //     userRefList.current?.reset();
              //   },
              // }}
            /> */}
            {/* <ProFormCascader
              width="xl"
              name="assignOrganizationIds"
              placeholder="选择单位"
              label="选择单位"
              popupClassName="popup"
              fieldProps={{
                options: articleOrganizations,
                showSearch: { filter },
                placement:'bottomLeft',
                multiple: true,
                removeIcon: true,
                allowClear: true,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
                onChange(value, selectOptions) {
                  setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                  userRefList.current?.reset();
                },
              }}
            /> */}
            {/* <ProFormDateRangePicker name="createdTimes" label="报送日期" allowClear fieldProps={{
              popupStyle: {
                width: 280
              }
            }} /> */}
          </LightFilter>
          {/* <ProFormCascader
              width="xl"
              name="assignOrganizationIds"
              placeholder="选择单位"
              style={{
                padding: '10px',
              }}
              formItemProps={{
                style: {
                  width: 250,
                  marginLeft: '18px',
                  marginBottom: '0px',
                },
              }}
              fieldProps={{
                options: articleOrganizations,
                showSearch: { filter },
                multiple: true,
                removeIcon: true,
                allowClear: true,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
                onChange(value, selectOptions) {
                  setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                  userRefList.current?.reset();
                },
              }}
            /> */}
          <ProList<CuesActiveData.ActivePage>
            header={false}
            headerTitle={
              <div
                style={{
                  display: 'flex',
                }}
              >
              </div>
            }
            className='tableActive'
            actionRef={userRefList}
            request={async (params = {}) => {
              if (params.organizationIds) {
                const organizationParentIds: string[] = [];
                let organizationIds: string[] = [];

                params.organizationIds.forEach((item: string | any[]) => {
                  if (item.length === 1) {
                    organizationParentIds.push(item[0]);
                  } else if (item.length > 1) {
                    organizationIds.push(item[1]);
                  }
                });
                organizationParentIds.forEach((id) => {
                  const ids = articleOrganizations.find((item) => item.id === id).children;
                  organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
                });
                params.articleOrganizationIds = organizationIds;
              }

              const response = await pageCuesActive({
                createdSource: 1,
                ...queryParam,
                ...params,
              });

              return Promise.resolve({
                data: response.data.data,
                total: response.data.total,
                success: response.code === 0,
              });
            }}
            pagination={{
              defaultPageSize: 8,
              showSizeChanger: false,
              showTotal: false,
              style: { textAlign: 'center' },
            }}
            showActions="hover"
            grid={{ gutter: 18, column: 1 }}
            onItem={(record: any) => {
              return {
                onMouseEnter: () => { },
                onClick: () => { },
              };
            }}
            renderItem={(item: CuesActiveData.ActivePage, index: number) => {
              return (
                <DetailsClue
                  item={item}
                  id={item.id}
                  onRefurbish={() => {
                    userRefList.current?.reload();
                  }}
                  triggerMode="card"
                  name={item.articleName}
                />
              );
            }}
            rowKey={'id'}
            toolBarRender={false}
            style={{ marginTop: 10 }}
          />
        </div>
      )}
      {tabActiveKey === 'TableSubmit' && <TableSubmit isEditable={false} />}
    </div>
  );
};
export default Clue;
